import datetime
import os
import uuid
from dataclasses import dataclass
from flask import  session, flash, current_app
from werkzeug.security import generate_password_hash, check_password_hash
from redis import Redis
from injector import inject
from src.util.token_util import AccessToken

from src.model import User
from src.pkg.sqlalchemy import SQLAlchemy



@inject
@dataclass
class UserService:
    db: SQLAlchemy
    redis_client: Redis

    def register(self, user: dict):
        username = user['username']
        password = user['password']
        hashed_password = generate_password_hash(password, method='pbkdf2:sha256')

        # 检查用户名是否存在
        user = self.db.session.query(User).filter_by(username=user["username"]).first()
        if user:
            flash('Username already exists.', 'danger')
            return -1

        new_user = User(username=username, password=hashed_password)
        self.db.session.add(new_user)
        self.db.session.commit()
        return 200



    def getuser_info(self):
        return self.db.session.query(User).filter(User.user_id== session["user_id"]).one_or_none()

    # 生成 JWT token
    def generate_token(self, user: dict):
        payload = {
            'user_id': user.user_id,
            'username': user.username,
            'exp': datetime.datetime.utcnow() + datetime.timedelta(seconds=current_app.config["JWT_EXPIRATION_DELTA"])
            # 设置过期时间
        }

        token = AccessToken.create_toklen(payload, current_app.config["SECRET_KEY"], 'HS256')
        return token

    # 解析 JWT token

    def login(self, user: dict):
        username = user["username"]
        password = user["password"]
        user = self.db.session.query(User).filter_by(username=username).first()
        # 检查用户名和密码是否匹配
        if user and check_password_hash(user.password, password):
            token = self.generate_token(user)
            session['user_id'] = user.user_id
            session['username'] = user.username
            flash('Login successful!', 'success')
            return token
        else:
            flash('Invalid username or password.', 'danger')
        return -1
